package methodref02;

import org.junit.Test;

import java.util.function.Consumer;
import java.util.function.Supplier;

/**
 * 实例方法(非静态方法)的引用:
 *  使用前提:
 *    引用的方法和Lambda表达式对应接口中的抽象方法形参类型要保持一致
 *  格式:
 *    对象名::方法名
 */
public class MethodRefDemo01 {
    Person p = new Person("老王");

    @Test
    public void test01() {
        //Supplier<String> s = () -> p.getName();
        Supplier<String> s = p::getName;
        System.out.println(s.get());
    }

    @Test
    public void test02(){
        //Consumer<String> c = name -> p.setName(name);
        Consumer<String> c = p::setName;
        c.accept("老王");
        System.out.println(p);
    }

    @Test
    public void test03(){
        String str = "abc";
        //Supplier<Integer> s = () -> str.length();
        Supplier<Integer> s = str::length;
        System.out.println(s.get());
    }

    @Test
    public void test04(){
        String str = "abc";
        Supplier<Character> s = () -> str.charAt(1);
        //Supplier<Character> s = str::charAt;//由于Lambda表达式对应的接口中的抽象方法的形参(get())
        //和String类中的charAt(int)形参类型不一致,所以不能使用实例方法(非静态方法)的引用格式
        System.out.println(s.get());
    }
}

/**
 public class MethodRefDemo01 {
    Person p = new Person("老王");
    class MethodRefDemo01$$Lambda$01 implements Supplier<String>{
        public String get(){
            return p.getName();
    }
 }

 class MethodRefDemo01$$Lambda$02 implements Consumer<String>{
    public void accept(String t){
         p.setName(t);
    }
 }

 class MethodRefDemo01$$Lambda$02 implements Supplier<Integer>{
    String str = "abc";
    public int get(){
        return str.length();
        }
     }
 }

 */

